#include<iostream>
#include<vector>
using namespace std;


class Solution {
public:
    int trap(vector<int>& height) {
        int l = 0; int r = 1;
        int len = height.size();
        vector<int> rem(len, 0);
        while (l < len) {
            while (r < len && height[r] < height[l]) {
                // rem[l] = height[r];
                r++;
            }
            if (r < len && height[r] >= height[l]) {
                for (int i = l; i < r; i++) {
                    rem[i] = height[l];
                }
                l = r - 1;
                r++;
            }
            l++;
        }
        l = len - 2; r = len - 1;
        while (r >= 0) {
            while (l >= 0 && height[l] < height[r]) {
                l--;
            }
            if (l >= 0 && height[l] >= height[r]) {
                for (int i = r; i > l; i--) {
                    rem[i] = height[r];
                }
                r = l + 1;
                l--;
            }
            r--;
        }

        int total_water = 0;
        for (int i = 0; i < len; i++) {
            total_water = max(total_water, total_water + rem[i] - height[i]);
        }
        return total_water;
    }
};